<template>
  <div>
    <div class="box-border p-12px">
      <el-form ref="formRef" :rules="rules" :model="form" class="mt-12px">
        <div>
          <SubTitle title="基本信息" />
          <!-- 文件 -->
          <template v-if="props.params.dataType === 'file'">
            <el-form-item label="文件名称" prop="fileName">
              <ns-input v-model="form.fileName" style="width: 300px" clearable />
            </el-form-item>
            <el-form-item label="文件类型" prop="fileType">
              <ns-input v-model="form.fileType" style="width: 300px" clearable />
            </el-form-item>
            <el-form-item label="文件大小" prop="fileSize">
              <ns-input v-model="form.fileSize" style="width: 300px" clearable />
            </el-form-item>
          </template>
          <template v-if="props.params.dataType === 'column'">
            <el-descriptions :column="1">
              <el-descriptions-item
                :label="item.label"
                v-for="(item, index) in columnDesc"
                :key="index"
              >
                <span>{{ props.params[item.key] || '--' }}</span>
              </el-descriptions-item>
            </el-descriptions>
          </template>
          <template v-if="props.params.dataType === 'table'">
            <el-descriptions :column="1">
              <el-descriptions-item
                :label="item.label"
                v-for="(item, index) in tableDesc"
                :key="index"
              >
                <span>{{ props.params[item.key] || '--' }}</span>
              </el-descriptions-item>
            </el-descriptions>
          </template>
          <el-form-item label="归属机构" prop="deptId">
            <el-cascader
              v-model="form.deptId"
              clearable
              placeholder="请选择归属机构"
              :options="options"
              :props="cascaderProps"
              filterable
              value-on-clear=""
              @change="deptChange"
            />
          </el-form-item>
          <el-form-item label="归属系统" prop="sysId">
            <el-cascader
              v-model="form.sysId"
              placeholder="请选择归属系统"
              :props="systemCascaderProps"
              value-on-clear=""
              :options="systemList"
              filterable
              clearable
              @change="sysChange"
            />
          </el-form-item>
          <el-form-item label="数据保护标准" prop="template">
            <el-select
              v-model="form.template"
              clearable
              placeholder="请选择数据标准"
              @change="templateChange"
            >
              <el-option
                v-for="(template, templateIndex) in templateList"
                :key="templateIndex"
                :label="template.dataStandardName"
                :value="template.id"
              />
            </el-select>
          </el-form-item>
        </div>
        <div class="mt-16px">
          <SubTitle title="分类分级信息">
            <!-- <el-button
              link
              type="primary"
              class="ml-12px"
              @click="openSample"
              v-if="props.params.dataType !== 'schema'"
              >查看抽样数据</el-button
            > -->
          </SubTitle>
          <el-form-item
            v-for="(item, index) in columnList"
            :label="item.name"
            :prop="`institutionFiled${item.index}`"
            :rules="[{ required: item.required == '1', message: `${item.name}不能为空` }]"
            :key="index"
          >
            <!-- {{ item.index }} -->
            <el-cascader
              :filter-method="sysFilterMethod"
              @change="(e) => classChange(e, index + 1)"
              placeholder="请选择分类"
              v-model="form[`institutionFiled${item.index}`]"
              :options="classOptions"
              :props="{
                value: 'field1',
                label: 'field1_name',
                checkStrictly: true,
                expandTrigger: 'hover',
                emitPath: false
              }"
              v-if="item.index == '1'"
              filterable
            />
            <!--            <el-select-->
            <!--              v-model="form[`institutionFiled${item.index}`]"-->
            <!--              placeholder="请选择"-->
            <!--              v-if="item.index == '1'"-->
            <!--              @change="institutionFiledChange(item.index)"-->
            <!--            >-->
            <!--              <el-option-->
            <!--                v-for="item in tempClassList"-->
            <!--                :key="item.key"-->
            <!--                :label="item.value"-->
            <!--                :value="item.key"-->
            <!--              />-->
            <!--            </el-select>-->

            <el-select
              v-model="form[`institutionFiled${item.index}`]"
              placeholder="请选择"
              v-else-if="item.index == '2'"
              @change="institutionFiledChange(item.index)"
            >
              <el-option
                v-for="citem in cascaderAllOptions?.[`field${item.index - 1}`]"
                :key="citem[`field${item.index}`]"
                :value="citem[`field${item.index}`]"
                :label="citem[`field${item.index}_name`]"
              />
            </el-select>
            <el-select
              v-model="form[`institutionFiled${item.index}`]"
              placeholder="请选择"
              clearable
              allow-create
              filterable
              v-else-if="item.index == '3' && dropdownData"
              @change="
                () => {
                  institutionFiledChange(item.index)
                  timeFiledChange()
                }
              "
            >
              <el-option
                v-for="citem in cascaderAllOptions?.[`field${item.index - 1}`]"
                :key="citem[`field${item.index}`]"
                :value="citem[`field${item.index}`]"
                :label="citem[`field${item.index}_name`]"
              />
            </el-select>
            <ns-input
              v-else-if="item.fillingMethod == '输入框'"
              v-model="form[`institutionFiled${item.index}`]"
              clearable
              placeholder="请输入"
              style="width: 200px"
            />
            <el-select
              v-model="form[`institutionFiled${item.index}`]"
              placeholder="请选择"
              v-else-if="item.fillingMethod == '选择器' && dropdownData"
              @change="institutionFiledChange(item.index)"
            >
              <el-option
                v-for="citem in cascaderAllOptions?.[`field${item.index - 1}`]"
                :key="citem[`field${item.index}`]"
                :value="citem[`field${item.index}`]"
                :label="citem[`field${item.index}_name`]"
              />
            </el-select>
            <el-date-picker
              v-else-if="item.fillingMethod == '日期'"
              value-format="YYYY-MM-DD HH:mm:ss"
              v-model="form[`institutionFiled${item.index}`]"
              type="date"
              placeholder="选择日期"
            />
          </el-form-item>
        </div>
        <div class="mt-16px">
          <el-form-item
            v-for="(item, index) in extendList"
            :label="item.name"
            :prop="`field${item.index}`"
            :rules="[{ required: item.required == '1', message: `${item.name}不能为空` }]"
            :key="index"
          >
            <el-select
              v-model="form[`field${item.index}`]"
              placeholder="请选择"
              v-if="item.index == '3'"
            >
              <el-option
                v-for="item in levelList"
                :key="item.levelCode"
                :label="item.levelName"
                :value="item.levelCode"
              />
            </el-select>
            <ns-input
              v-else-if="item.fillingMethod == '输入框'"
              v-model="form[`field${item.index}`]"
              clearable
              placeholder="请输入"
              style="width: 200px"
            />
            <el-select
              v-else-if="item.fillingMethod == '选择器'"
              clearable
              v-model="form[`field${item.index}`]"
              placeholder="请选择"
            >
              <el-option
                v-for="(option, optionIndex) in item.presetContentMap"
                :key="optionIndex"
                :label="option"
                :value="option"
              />
            </el-select>
            <el-date-picker
              v-else-if="item.fillingMethod == '日期'"
              value-format="YYYY-MM-DD HH:mm:ss"
              v-model="form[`field${item.index}`]"
              type="date"
              placeholder="选择日期"
              @change="dateChange(item.index)"
            />
          </el-form-item>
        </div>
      </el-form>
    </div>
    <div>
      <el-button type="primary" @click="confirm">审核申请</el-button>
      <el-button @click="closeOutDrawer">取消</el-button>
    </div>
  </div>
</template>
<script lang="ts" setup>
import SubTitle from '@/components/SubTitle/index.vue'
import { assetMessagePassUpdateAndAudit } from '@/api/assetPass/index'
import { infoPage } from '@/api/dataStandards/info/index'
import * as assuranceApi from '@/api/dataStandards/assurance/index'
import { classificationTree } from '@/api/dataStandards/classification/index'
import { levelPage } from '@/api/strategyManage/level/index'
import {
  valueConfGetByValue,
  valueConfGetByValueTree,
  valueConfFieldValue
} from '@/api/dataStandards/assuranceValue/index'
import { getSimpleDeptList } from '@/api/system/dept'
import { getSimpleSystemList } from '@/api/asset/taskManage'
import { dataStandardsPage } from '@/api/dataStandards/standards/index'
import { handleTree } from '@/utils/tree'
import { getProcessDefinitionOne } from '@/api/bpm/definition'
import useCascader from '@/hooks/event/useCascader'
import dayjs from 'dayjs'
const message = useMessage() // 消息弹窗
const { proxy } = getCurrentInstance() as any
const route = useRoute()

const columnDesc = [
  { label: '字段名称：', key: 'column' },
  { label: '字段类型：', key: 'columnType' },
  { label: '字段描述：', key: 'comment' },
  { label: '所属表：', key: 'table' },
  { label: '所属schema：', key: 'schema' },
  { label: '所属库：', key: 'database' }
]
const tableDesc = [
  { label: '表名称：', key: 'table' },
  { label: '表描述：', key: 'remark' },
  { label: '所属schema：', key: 'schema' },
  { label: '所属库：', key: 'database' }
]

const cascaderProps = ref({
  checkStrictly: true,
  label: 'name',
  value: 'id',
  children: 'children',
  emitPath: false
})
const systemCascaderProps = {
  checkStrictly: true,
  label: 'value',
  value: 'id',
  children: 'children',
  emitPath: false
}
const classOptions = ref([])
const formRef = ref()
const props = defineProps({
  params: {
    type: Object,
    default: () => {}
  },
  closeOutDrawer: Function
})
const classificationCascaderProps = ref({
  checkStrictly: true,
  label: 'cnName',
  value: 'id',
  children: 'children',
  emitPath: false
})

const form = ref({
  id: '',
  template: '',
  handClassification: '',
  handLevel: '',
  handImportance: '公开数据',
  sensitiveDeadline: '1',
  deadlineLevel: '',
  // extendContent: '',
  deadlineTimeNum: '',
  deadlineTimeUnit: '',
  secretDeadline: '',
  secretStartTime: '',
  deadlineTime: '',
  deptId: '',
  sysId: ''
})
const isRequired = computed(() => {
  return !form.value.deptId && !form.value.sysId
})
const rules = computed(() => ({
  sensitiveDeadline: [{ required: true, message: '敏感期限不能为空', trigger: 'change' }],
  deadlineTimeNum: [{ required: true, message: '时长不能为空', trigger: 'blur' }],
  deadlineTimeUnit: [{ required: true, message: '时间单位不能为空', trigger: 'blur' }],
  deadlineLevel: [{ required: true, message: '到期后敏感级别不能为空', trigger: 'blur' }],
  handClassification: [{ required: true, message: '分类不能为空', trigger: 'blur' }],
  handLevel: [{ required: true, message: '分级不能为空', trigger: 'blur' }],
  sysId: [{ required: isRequired.value, message: '归属系统不能为空', trigger: 'change' }],
  deptId: [{ required: isRequired.value, message: '归属机构不能为空', trigger: 'change' }]
}))
const extendList = ref([
  {
    index: '1',
    name: '',
    required: '',
    fillingMethod: '输入框',
    presetContentMap: []
  }
])

// 数据选择修改后，控制后面字段的修改
// const institutionFiledChange = (index) => {
//   updateFields(`field${index}`, form.value[`institutionFiled${index}`])
// }
// // 更新字段
// function updateFields(selectedField, selectedValue) {
//   const Index = parseInt(selectedField.replace('field', ''))
//   // 找到与选定字段值匹配的第一个对象
//   const matchedItem = downLists.value.find((item) => item[selectedField] === selectedValue)
//   if (matchedItem) {
//     // 更新其他字段的值（条件是只更新操作字段之后的字段）
//     Object.keys(matchedItem).forEach((key) => {
//       if (key !== selectedField && key.startsWith('field')) {
//         const fieldIndex = parseInt(key.replace('field', ''))
//         if (Index < fieldIndex)
//           // 更新其他字段的值为匹配的对象的值
//           form.value[`institutionFiled${fieldIndex}`] = matchedItem[key]
//       }
//     })
//   }
// }

const dateChange = (index) => {
  if (index == '1') {
    timeFiledChange()
  }
}

const timeFiledChange = () => {
  let convertedTime = convertTimeFormat(form.value.institutionFiled3)
  if (!convertedTime) {
    let currentClass = allLevelList.value.find(
      (item) => item.levelCode == form.value.institutionFiled2
    )
    convertedTime =
      convertTimeFormat(currentClass?.deadlineTimeNum + currentClass?.deadlineTimeUnit) || {}
  }
  form.value.field2 = dayjs(form.value.field1)
    .add(Number(convertedTime.num), convertedTime.unit)
    .format('YYYY-MM-DD HH:mm:ss')
}
// 时间格式转换
function convertTimeFormat(timeString) {
  if (!timeString) {
    return
  }
  // 匹配数字和单位部分的正则表达式
  const regex = /(\d+)\s*([^0-9\s]+)/
  // 匹配结果
  const match = timeString.match(regex)
  const unitMap = new Map([
    ['年', 'year'],
    ['月', 'month'],
    ['天', 'day'],
    ['日', 'day']
  ])

  // 如果匹配成功，则返回 num 和 unit 对象
  if (match) {
    //单位不对则退出
    if (!unitMap.get(match[2])) {
      return false
    }
    return {
      num: parseInt(match[1]),
      unit: unitMap.get(match[2])
    }
  } else {
    // 如果匹配失败，返回空对象
    return false
  }
}

const templateChange = async (e) => {
  await getClassLevelList(form.value.template)
  getInfoList(form.value.template)
  getAssuranceList(form.value.template)
  getClassificationTree(form.value.template)
  getDownList(form.value.template)
  form.value.templateName = templateList.value.find((item) => {
    return item.id == e
  }).dataStandardName
}
const deptChange = (e) => {
  form.value.deptName = findNode(options.value, e)?.name
}
const sysChange = (e) => {
  form.value.sysName = findNode(systemList.value, e)?.value
}

function findNode(nodes, targetId) {
  for (let node of nodes) {
    // 检查当前节点
    if (node.id == targetId) {
      return node // 找到匹配项，返回节点
    }

    // 如果没有在当前节点找到，递归检查子节点
    if (node.children && node.children.length > 0) {
      const found = findNode(node.children, targetId)
      if (found) {
        return found // 如果在子节点中找到，返回找到的节点
      }
    }
  }

  return null // 没有找到匹配项
}

function filterFileFields(fileData) {
  // 获取需要保留的 index 列表
  const institutionIndexes = columnList.value.map((item) => item.index)
  const fieldIndexes = extendList.value.map((item) => item.index)

  // 创建新对象（不修改原对象）
  const result = { ...fileData }

  // 处理 institutionFiledX 字段
  for (let i = 1; i <= 20; i++) {
    const key = `institutionFiled${i}`
    if (!institutionIndexes.includes(i)) {
      result[key] = ''
    }
  }

  // 处理 fieldX 字段
  for (let i = 1; i <= 20; i++) {
    const key = `field${i}`
    if (!fieldIndexes.includes(i)) {
      result[key] = ''
    }
  }
  result.handClassification = result.institutionFiled1 || ''
  result.handLevel = result.institutionFiled2 || ''
  result.secretDeadline = result.institutionFiled3 || ''
  result.secretStartTime = result.field1 || ''
  result.deadlineTime = result.field2 || ''
  result.deadlineLevel = result.field3 || ''

  return result
}

const confirm = async () => {
  form.value.handClassification = form.value.institutionFiled1
  form.value.handLevel = form.value.institutionFiled2
  form.value.secretDeadline = form.value.institutionFiled3
  form.value.secretStartTime = form.value.field1
  form.value.deadlineTime = form.value.field2
  form.value.deadlineLevel = form.value.field3
  form.value.auditType =
    props.params.dataType === 'column'
      ? 'passColumn'
      : props.params.dataType === 'table'
        ? 'passTable'
        : 'passFile'
  const formData = filterFileFields(form.value)
  let recheckObj = {}
  for (let i = 1; i <= 20; i++) {
    recheckObj[`recheckField${i}`] = formData[`field${i}`]
    recheckObj[`recheckInstitutionFiled${i}`] = formData[`institutionFiled${i}`]
  }
  formData.recheckField = JSON.stringify(recheckObj)
  // 扩展字段
  formRef.value.validate(async (valid) => {
    if (valid) {
      const data = await assetMessagePassUpdateAndAudit({
        ...formData,
        deptId: form.value.deptId == '' ? '0' : form.value.deptId
      })
      console.log('data', data)
      if (data) {
        message.success('修改成功')
        props.params.callBack()
        props.closeOutDrawer()
      }
    }
  })
}

// 获取模板扩展字段列表
const getInfoList = async (template) => {
  const data = await infoPage({
    page: 1,
    pageSize: 20,
    dataStandardId: template || props.params.template,
    display: '1'
  })
  extendList.value = data?.map((item) => {
    return {
      ...item,
      presetContentMap: item.presetContent ? JSON.parse(item.presetContent) : []
    }
  })
  getLevelList()
}

const columnList = ref([
  {
    index: '1',
    name: '',
    required: '',
    fillingMethod: '输入框',
    presetContentMap: []
  }
])
// 获取制度信息字段列表
const getAssuranceList = async (template) => {
  const data = await assuranceApi.assurancePage({
    dataStandardId: template || props.params.template,
    display: 1,
    page: 1,
    pageSize: 20
  })
  if (data.length > 0) {
    columnList.value = data
  } else {
    columnList.value = []
  }
}

// 获取模板下的分类树
const classificationList = ref([])
const getClassificationTree = async (template) => {
  const data = await classificationTree({
    standardId: template || props.params.template
  })
  classificationList.value = data
}

// 获取等级下拉列表
const levelList = ref([])
const allLevelList = ref([])
const getLevelList = async () => {
  const { data } = await levelPage({ page: 1, pageSize: 999 })
  const deadLineConf = extendList.value.find((item) => item.index === 3)
  if (deadLineConf && deadLineConf.presetContent && deadLineConf.presetContent !== '[]') {
    const presetCodes = JSON.parse(deadLineConf.presetContent)
    levelList.value = data.filter((item) => presetCodes.includes(item.levelCode))
  } else {
    levelList.value = data
  }
  allLevelList.value = data
}
let classChange = async () => {}
let institutionFiledChange = async () => {}
/** 查询下拉列表 */
const cascaderAllOptions = ref([])
const flattenDownList = ref([])
const downLists = ref([])
const dropdownData = ref([])
// const getDownList = async (template) => {
//   const data = await valueConfGetByValue({
//     dataStandardId: template || props.params.template
//   })
//   let {inFiledChange, typeChange, byValuetreeData, byValueData, cascaderSelectOptions } =await useCascader({treeData,data,listValue:ref([form.value]),tempLevelList:tempLevelList.value})
//   if (data.length > 0) {
//     downLists.value = data
//     dropdownData.value = convertToDropdownData(downLists.value)
//   } else {
//     downLists.value = []
//   }
// }
const getDownList = async (template) => {
  let data = await valueConfGetByValue({
    dataStandardId: template
  })
  let treeData = await valueConfGetByValueTree({
    dataStandardId: template
  })
  let { inFiledChange, typeChange, byValuetreeData, byValueData, cascaderSelectOptions } =
    await useCascader({
      treeData,
      data,
      listValue: ref([form.value]),
      tempLevelList: tempLevelList.value
    })

  classChange = typeChange
  institutionFiledChange = inFiledChange
  cascaderAllOptions.value = cascaderSelectOptions.value[0]
  if (data.length > 0) {
    downLists.value = byValueData
    flattenDownList.value = byValuetreeData
    dropdownData.value = convertToDropdownData(downLists.value)
  } else {
    downLists.value = data
    flattenDownList.value = []
    classOptions.value = setClassOptionsMap(flattenDownList.value)
  }
}
const convertToDropdownData = (data) => {
  const dropdownData = {}
  Object.keys(data[0]).forEach((key) => {
    if (key.startsWith('field')) {
      dropdownData[key] = Array.from(
        new Set(data.map((item) => item[key]).filter((value) => value !== ''))
      )
    }
  })
  return dropdownData
}

const openSample = () => {
  if (props.params.dataType === 'column') {
    proxy?.$Drawer({
      params: {
        samples: props.params.samples
      },
      title: `查看抽样数据`,
      size: '30%',
      component: import('@/views/asset/assetList/components/columnSamples.vue')
    })
  } else if (props.params.dataType === 'file') {
    proxy?.$Drawer({
      params: props.params,
      title: `查看抽样数据`,
      size: '30%',
      component: import('@/views/asset/assetList/components/fileSamples.vue')
    })
  } else if (props.params.dataType === 'table') {
    proxy?.$Drawer({
      params: props.params,
      title: `查看字段分级`,
      size: '30%',
      component: import('@/views/asset/assetList/components/tableSamples.vue')
    })
  }
}

const tempClassList = ref([])
const tempLevelList = ref([])
const getClassLevelList = async (template) => {
  tempClassList.value = await valueConfFieldValue({
    dataStandardId: template || props.params.template,
    type: '1'
  })
  tempLevelList.value = await valueConfFieldValue({
    dataStandardId: template || props.params.template,
    type: '2'
  })
}

const options = ref()
const getDeptList = async () => {
  const data = await getSimpleDeptList()
  options.value = data
}

const systemList = ref()
const getSystemList = async () => {
  const data = await getSimpleSystemList({})
  systemList.value = handleTree(data, 'id', 'pid')
}

const templateList = ref([])
const getTemplateList = async () => {
  const { data } = await dataStandardsPage({
    page: 1,
    pageSize: 999,
    type: props.params.dataType === 'file' ? 0 : 1,
    status: '1'
  })
  templateList.value = data
}

const processList = ref([])
const getProcessList = async () => {
  try {
    processList.value = await getProcessDefinitionOne({
      assetId: props.params.id,
      assetType: props.params.dataType === 'file' ? 'file' : 'db',
      deptId: props.params.deptId == '' ? '0' : props.params.deptId,
      sysId: props.params.sysId
    })
    if (processList.value.length) {
      const processId = processList.value[0].id
      const firstColonIndex = processId.indexOf(':')
      form.value.processDefinitionKey = processId.slice(0, firstColonIndex)
    }
  } finally {
  }
}

const handleCheckclassOptions = (list, targetValue) => {
  for (const item of list) {
    // 使用 for...of 遍历数组
    if (item.field1 === targetValue) {
      return true // 找到直接返回
    }
    // 检查是否存在 children 并且是数组且长度大于0
    if (item.children && Array.isArray(item.children) && item.children.length > 0) {
      // 递归检查子节点，并立即返回结果
      const found = handleCheckclassOptions(item.children, targetValue)
      if (found) return true
    }
  }
  return false // 遍历完所有项未找到
}
watch(
  () => [tempClassList.value, downLists.value],
  () => {
    if (downLists.value.length > 0 && tempClassList.value.length > 0) {
      classOptions.value = setClassOptionsMap(flattenDownList.value)
      const isInclude = handleCheckclassOptions(classOptions.value, form.value.institutionFiled1)

      if (form?.value?.institutionFiled1 && !isInclude) {
        form.value.institutionFiled1 = classOptions.value[0]?.field1
        classChange(classOptions.value[0]?.field1, 1)
      } else {
        classChange(form.value.institutionFiled1, 1)
      }
    }
  }
)

const setClassOptionsMap = (data) => {
  return data.map((item) => {
    item.field1_name = tempClassList.value.find((fitem) => fitem.key == item.field1).value
    item.disabled = item.isSelect == '0'
    item.children.length && setClassOptionsMap(item.children)
    return item
  })
}
onMounted(async () => {
  await getClassLevelList(props.params.template)

  getInfoList(props.params.template),
    getAssuranceList(props.params.template),
    getClassificationTree(props.params.template),
    getDownList(props.params.template),
    getDeptList(),
    getSystemList(),
    getTemplateList(),
    getProcessList()

  const processDefinitionKey = form.value.processDefinitionKey
  nextTick(() => {
    form.value = props.params
    form.value.deptId = form.value.deptId == '0' ? '' : form.value.deptId
    form.value.processDefinitionKey = processDefinitionKey
    if (props.params.type === '自动') {
      form.value.institutionFiled1 = props.params.classification
      form.value.institutionFiled2 = String(props.params.level)
    }
    // 等级下拉回显
    if (form.value.field3) {
      form.value.field3 = Number(form.value.field3)
    }
  })
})
</script>

<style scoped lang="scss">
:deep(.el-table .el-form-item--default) {
  margin-bottom: 0 !important;
}
</style>
